<template>
	<scroll-view class="mine-container" scroll-y>

	<!-- 顶部用户信息区域 -->
	<view class="user-section">
		<view class="user-info" @click="handleUserClick">
			<image class="avatar" :src="isLogin ? userStore.userInfo.avatar : '/static/wode 2_slices/zu428.png'"></image>
			<view class="user-text">
				<text class="login-text">{{ isLogin ? userStore.userInfo.nickName : '立即登录' }}</text>
				<text class="sub-text">{{ isLogin ? userStore.userInfo.phone : '登录后可收藏喜欢的菜谱' }}</text>
			</view>
		</view>

		<view class="vip-card" @click="handleVipClick">
			<view class="vip-left">
				<text class="vip-text">{{ isLogin && userStore.userInfo.isVip ? '尊贵VIP' : '升级为VIP' }}</text>
			</view>
			<text class="vip-arrow">❯</text>
		</view>
	</view>

		<!-- 功能导航栏 -->
		<view class="mine-nav">
			<view class="nav-item" v-for="item in navList" :key="item.id" @click="handleClick(item)">
				<image class="nav-icon" :src="item.icon"></image>
				<text class="nav-text">{{ item.name }}</text>
			</view>
		</view>

	<!-- 配料表区域 -->
	<view class="ingredient-section" v-if="isLogin && collections.length > 0">
		<!-- 菜谱标签栏 -->
		<view class="recipe-tabs">
			<scroll-view scroll-x class="tabs-scroll" show-scrollbar="false">
				<text 
					:class="['tab-item', activeRecipeIndex === -1 ? 'active' : '']"
					@click="activeRecipeIndex = -1">
					所有食材
				</text>
				<text 
					v-for="(item, index) in collections" 
					:key="item._id"
					:class="['tab-item', activeRecipeIndex === index ? 'active' : '']"
					@click="activeRecipeIndex = index">
					{{ item.name }}
				</text>
			</scroll-view>
		</view>

		<!-- 配料列表 -->
		<view class="ingredient-content">
			<!-- 所有食材（activeRecipeIndex === -1） -->
			<view v-if="activeRecipeIndex === -1" class="all-ingredients">
				<view v-for="(item, index) in collections" :key="item._id" class="recipe-group">
					<view class="recipe-divider" v-if="index > 0"></view>
					<view class="ingredient-item" v-for="(ingredient, idx) in item.ingredient" :key="idx">
						<text class="ingredient-name">{{ ingredient.name }}</text>
						<text class="ingredient-number">{{ ingredient.number }}</text>
					</view>
				</view>
			</view>

			<!-- 单个菜谱的配料 -->
			<view v-else-if="currentRecipe && currentRecipe.ingredient" class="single-recipe-ingredients">
				<view class="ingredient-item" v-for="(ingredient, idx) in currentRecipe.ingredient" :key="idx">
					<text class="ingredient-name">{{ ingredient.name }}</text>
					<text class="ingredient-number">{{ ingredient.number }}</text>
				</view>
			</view>

			<!-- 无配料信息 -->
			<view v-else class="no-ingredient">
				<text>该菜谱暂无配料信息</text>
			</view>
		</view>
	</view>

	<!-- 空状态 -->
	<view v-if="isLogin && collections.length === 0" class="empty-state">
		<text class="empty-icon">❤️</text>
		<text class="empty-text">还没有收藏任何菜谱</text>
		<text class="empty-hint">快去搜索页面收藏喜欢的菜谱吧~</text>
	</view>

	<!-- 退出登录按钮 -->
	<view v-if="isLogin" class="logout-section">
		<u-button type="error" shape="circle" text="退出登录" @click="handleLogout" plain></u-button>
	</view>
	</scroll-view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue'
	import {
		onShow
	} from '@dcloudio/uni-app'
	import {
		useUserStore
	} from '@/store/user'
	import {
		getMyCollections
	} from '@/api/userApi'

	const userStore = useUserStore()

	// 判断是否登录 - 直接从本地存储读取 token
	const isLogin = computed(() => {
		const localToken = uni.getStorageSync('token')
		return !!localToken && !!userStore.userInfo._id
	})

	// 导航数据（静态）
	const navList = ref([{
			id: 1,
			name: '我的收藏',
			icon: '/static/chuanbei_slices/shoucamg.png'
		},
		{
			id: 2,
			name: '浏览记录',
			icon: '/static/chuanbei_slices/liulan.png'
		},
		{
			id: 3,
			name: '点赞',
			icon: '/static/chuanbei_slices/xing .png'
		}
	])

	// 我的收藏列表
	const collections = ref([])
	
	// 当前选中的菜谱索引（-1表示所有食材）
	const activeRecipeIndex = ref(-1)
	
	// 当前选中的菜谱
	const currentRecipe = computed(() => {
		if (activeRecipeIndex.value === -1 || !collections.value.length) {
			return null
		}
		return collections.value[activeRecipeIndex.value]
	})

	onShow(async () => {
		const localToken = uni.getStorageSync('token')
		
		console.log('=== 个人中心 onShow ===')
		console.log('本地 Token:', localToken ? '存在' : '不存在')
		console.log('UserInfo._id:', userStore.userInfo._id)
		console.log('登录状态:', isLogin.value)
		
		// 如果有 token，刷新用户信息
		if (localToken && userStore.userInfo._id) {
			await loadUserData()
		}
	})


	// 加载用户数据
	const loadUserData = async () => {
		try {
			if (!userStore.userInfo._id) {
				console.log('用户ID不存在，跳过加载')
				return
			}
			
			// 加载我的收藏
			const res = await getMyCollections(userStore.userInfo._id)
			console.log('我的收藏返回:', res)
			if (res.code === 200) {
				collections.value = res.data || []
			}
		} catch (err) {
			console.error('加载用户数据失败', err)
		}
	}

	// 点击用户头像区域
	const handleUserClick = () => {
		if (!isLogin.value) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		} else {
			// 已登录，可以跳转到编辑资料页面
			uni.showToast({
				title: '编辑资料功能待开发',
				icon: 'none'
			})
		}
	}

	// 点击VIP卡片
	const handleVipClick = () => {
		const localToken = uni.getStorageSync('token')
		if (!localToken) {
			uni.showModal({
				title: '提示',
				content: '请先登录',
				confirmText: '去登录',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}
				}
			})
			return
		}
		
		// TODO: 跳转到VIP充值页面
		uni.showToast({
			title: 'VIP功能待开发',
			icon: 'none'
		})
	}

	const handleClick = (item) => {
		// 检查登录状态（直接从本地存储读取）
		const localToken = uni.getStorageSync('token')
		if (!localToken) {
			uni.showModal({
				title: '提示',
				content: '请先登录',
				confirmText: '去登录',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}
				}
			})
			return
		}

		console.log('点击菜单:', item.name)
		
		// 根据不同的菜单项跳转
		switch (item.id) {
			case 1:
				// 我的收藏
				uni.showToast({
					title: '收藏功能待开发',
					icon: 'none'
				})
				break
			case 2:
				// 浏览记录
				uni.showToast({
					title: '浏览记录功能待开发',
					icon: 'none'
				})
				break
			case 3:
				// 点赞
				uni.showToast({
					title: '点赞功能待开发',
					icon: 'none'
				})
				break
		}
	}

	// 退出登录
	const handleLogout = () => {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					userStore.logout()
				}
			}
		})
	}


</script>

<style lang="scss" scoped>
	.mine-container {
		background-color: #f7f7f7;
		min-height: 100vh;
	}

	/* 用户信息区域 */
	.user-section {
		background-color: #fff;
		padding: 40rpx 32rpx 20rpx;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.user-info {
		display: flex;
		align-items: center;
	}

	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.user-text {
		display: flex;
		flex-direction: column;
	}

	.login-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.sub-text {
		font-size: 24rpx;
		color: #999;
		margin-top: 6rpx;
	}

	.vip-card {
		position: relative;
		width: 100%;
		height: 120rpx;
		margin-top: 30rpx;
		border-radius: 16rpx;
		overflow: hidden;

		/* 使用背景图片铺满容器 */
		background: url('/static/wode 1_slices/mengbanzu87.png') no-repeat center;
		background-size: cover;

		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 32rpx;
	}

	.vip-text {
		color: #b7852a;
		font-size: 30rpx;
		font-weight: bold;
		margin-left: 48rpx;
		letter-spacing: 2rpx;
	}

	.vip-arrow {
		color: #b7852a;
		font-size: 36rpx;
		transform: translateY(2rpx);
		margin-right: 48rpx;
	}


	/* 导航栏 */
	.mine-nav {
		background-color: #fff;
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding: 24rpx 0;
		border-top: 1rpx solid #f0f0f0;
		border-bottom: 1rpx solid #f0f0f0;
		margin-top: 20rpx;
	}

	.nav-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.nav-icon {
		width: 50rpx;
		height: 50rpx;
		margin-bottom: 10rpx;
	}

	.nav-text {
		font-size: 26rpx;
		color: #555;
	}

	/* 我的收藏区域 */
	.collection-section {
		background-color: #fff;
		margin-top: 20rpx;
		padding: 32rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.collection-count {
			font-size: 24rpx;
			color: #999;
		}
	}

	/* 收藏列表 */
	.collection-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.collection-item {
		display: flex;
		background: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		transition: all 0.3s;

		&:active {
			transform: scale(0.98);
		}
	}

	.collection-img {
		width: 200rpx;
		height: 200rpx;
		object-fit: cover;
		flex-shrink: 0;
	}

	.collection-info {
		flex: 1;
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.collection-name {
		font-size: 30rpx;
		font-weight: 600;
		color: #333;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		line-height: 1.4;
		margin-bottom: 8rpx;
	}

	.collection-meta {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-bottom: 8rpx;

		.meta-item {
			font-size: 24rpx;
			color: #666;
		}
	}

	.collection-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 8rpx;

		.tag {
			background: #f5f5f5;
			color: #666;
			font-size: 22rpx;
			padding: 4rpx 12rpx;
			border-radius: 8rpx;
		}
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 0;

		.empty-icon {
			font-size: 120rpx;
			margin-bottom: 20rpx;
			opacity: 0.5;
		}

		.empty-text {
			font-size: 28rpx;
			color: #999;
			margin-bottom: 8rpx;
		}

		.empty-hint {
			font-size: 24rpx;
			color: #ccc;
		}
	}

	/* 配料表区域 */
	.ingredient-section {
		background-color: #fff;
		margin-top: 20rpx;
		padding-bottom: 40rpx;
	}

	.recipe-tabs {
		border-bottom: 1rpx solid #f0f0f0;
		padding: 20rpx 0;

		.tabs-scroll {
			white-space: nowrap;
			padding: 0 32rpx;

			.tab-item {
				display: inline-block;
				margin-right: 40rpx;
				font-size: 28rpx;
				color: #666;
				padding-bottom: 16rpx;
				position: relative;

				&.active {
					color: #ff6600;
					font-weight: 600;

					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 0;
						right: 0;
						height: 4rpx;
						background: #ff6600;
						border-radius: 2rpx;
					}
				}
			}
		}
	}

	.ingredient-content {
		padding: 20rpx 32rpx;
	}

	.ingredient-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 0;
		border-bottom: 1rpx solid #f5f5f5;

		&:last-child {
			border-bottom: none;
		}

		.ingredient-name {
			font-size: 28rpx;
			color: #333;
			flex: 1;
		}

		.ingredient-number {
			font-size: 28rpx;
			color: #888;
			text-align: right;
		}
	}

	.recipe-group {
		&:not(:first-child) {
			margin-top: 20rpx;
		}
	}

	.recipe-divider {
		height: 20rpx;
		background-color: #f7f7f7;
		margin: 0 -32rpx;
	}

	.no-ingredient {
		padding: 80rpx 0;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}

	/* 退出登录区域 */
	.logout-section {
		padding: 40rpx 32rpx;
		background-color: #fff;
		margin-top: 20rpx;
	}
</style>